'''
Created on Mar 9, 2013

@author: Gabriel
'''
import json
import random

# Global instance of the database to be used everywhere around
DATA = None

__DB_FILE = 'C:/Users/Gabriel/git/relaxee/relaxeeDbBuilder/videosDatabase.json'

def __loadDatabase():
    global DATA
    with open(__DB_FILE, mode='r') as f :
        rawData = f.read();
        DATA = json.loads(rawData)
        print DATA


def __saveDatabase():
    global DATA
    print DATA
    with open(__DB_FILE, mode='w') as dbFile :
        serialized = json.dumps(DATA, sort_keys=True, indent=4, separators=(',', ': '))
        print serialized
        dbFile.write(serialized)


def createDatabase(newData):
    global DATA
    DATA = newData
    __saveDatabase()

def __randomIndex(array):
    return random.randint(0, len(array)  - 1)
    

# Queries
def getRandomMoviePath():
    randomMovie = DATA['movies'][__randomIndex(DATA['movies'])]
    return randomMovie


def getRandomEpisodePath():
    randomShow = DATA['shows'][__randomIndex(DATA['shows'])]
    randomEpisode = randomShow['episodes'][__randomIndex(randomShow['episodes'])]
    return randomEpisode

def __seekVideoInCategory(videoName, category):
    for video in DATA[category] : 
        if video['name'] == videoName :
            return video
        
        
def getVideo(videoName):
    video = __seekVideoInCategory(videoName, 'shows')
    if not video :
        video = __seekVideoInCategory(videoName, 'movies')

    # Gets the path to the current episode
    return video

#
# Increments the current episode and overflows back to initial episode
#
def incrementCurrentEpisode(showName):
    for show in DATA['shows'] : 
        if show['name'] == showName :
            show['currentEpisode'] = (show['currentEpisode'] + 1) % len(show['episodes'])
            __saveDatabase()
            
#
# Initialize DB instance
#
__loadDatabase()
#print (getRandomEpisodePath())
#print (getRandomMoviePath())
#print (getCurrentEpisodePath("Richard Hammond's Invisible Worlds"))
#print (incrementCurrentEpisode("Richard Hammond's Invisible Worlds"))